package com.wushi.lenovo.asia5b.app_config;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;

import com.mvp.dagger.modules.NetworkModule;
import com.mvp.utils.JsonUtil;
import com.wushi.lenovo.asia5b.app_http.ApiService;
import com.wushi.lenovo.asia5b.app_model.other.UserInfo;
import com.wushi.lenovo.asia5b.app_ui.login.activity.LoginThridActivity;

import io.reactivex.BackpressureStrategy;
import io.reactivex.Flowable;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subjects.PublishSubject;
import io.reactivex.subjects.Subject;

import static timber.log.Timber.d;

/**
 * Created by zhangyuncai on 2019/11/29.
 * todo :当更新用户信息后,通知其他位置
 */
public class UserRepository {
    private final static UserRepository userRepository = new UserRepository();
    ;

    private static synchronized UserRepository getInstance() {
        return userRepository;
    }

    private Subject<UserInfo> userInfoSubject;
    private final ApiService apiService;
    private long lastGetUserInfoTime = 0;

    public UserRepository() {
        userInfoSubject = PublishSubject.create();
        apiService = NetworkModule.getRetrofit().create(ApiService.class);
    }


    /**
     * 订阅数据监听
     *
     * @return
     */
    public static Flowable<UserInfo> getUserInfoOB() {
        return getInstance().userInfoSubject.toFlowable(BackpressureStrategy.LATEST);
    }

    public static void setUserInfo(UserInfo userInfo) {
        getInstance().setCurrentUserInfo(userInfo);
    }


    /**
     * 个人信息是否为null
     * true:空
     *
     * @return
     */
    public static boolean isLogin() {
        if (UserInfo.getMemberId() > 0 && (!TextUtils.isEmpty(UserInfo.getUserToken()))) {//只需要拥有user_id和userToken,个人信息就不是空
            return true;
        }
        return false;
    }

    public static boolean isLogin(Context context) {
        if (isLogin()) {
            return true;
        }
        if (context != null) {
            context.startActivity(new Intent(context, LoginThridActivity.class));
        }
        return false;
    }


    /**
     * 从服务器更新用户资料
     */
    public static void updateUserInfo() {
        getInstance().getUserInfoByNet();
    }

    /**
     * 从服务器更新用户资料
     */
    private void getUserInfoByNet() {
        if (!isLogin()) {
            d("--->>>>>>>>---没登录");
            return;
        }
        if ((System.currentTimeMillis() - lastGetUserInfoTime) < 1000) {
            return;
        }
        lastGetUserInfoTime = System.currentTimeMillis();
        apiService.getUserInfo(UserInfo.getMemberId())
                .map(userInfoResultModel -> userInfoResultModel.getData())
                .subscribeOn(Schedulers.io())
                .subscribe(userInfo -> {
                    //仅仅更新UserInfo,不涉及到登录/退出
                    if (userInfo != null) {
                        //TODO 重新赋值userToken
                        userInfo.setUserToken(UserInfo.getUserToken());
                        setCurrentUserInfo(userInfo);
                    }
                }, throwable -> {
                    throwable.printStackTrace();
                });
    }


    /**
     * 当前用户
     * 登录/退出用户信息唯一方法
     * todo UserInfo必须包含userToken
     *
     * @param userInfo
     */
    private void setCurrentUserInfo(UserInfo userInfo) {
        if (userInfo == null) {
            AppExtendsKt.setCacheUserInfo(new UserInfo());
            d("--->>>>>>>>---用户登出");
        } else {
            d("--->>>>>>>>---登录用户信息" + JsonUtil.INSTANCE.anyToJson(userInfo));
            AppExtendsKt.setCacheUserInfo(userInfo);
        }
        getInstance().userInfoSubject.onNext(UserInfo.getUserInfo());
    }

}
